package com.lanou3g.Code0517.study.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@WebServlet(name = "SessionServlet01",urlPatterns = "/session01")
public class SessionServlet01 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //如果可以使用已有session,则使用已有session
        //如果没有创建session,则会自动创建一个session
        //并分配JSESSIONID
        HttpSession session = request.getSession();
        //获取创建时间
        //java中时间是从1970年开始 经过的毫秒数
        long time = session.getCreationTime();
        Date date = new Date(time);
       //获session的时间
//        int year = date.getYear();//年
//        int month = date.getMonth();//月
//        int day = date.getDay();//日
//        Calendar.getInstance().get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println(sdf.format(new Date(time)));
        //获取sessionID
        String sessionID = session.getId();
        Cookie cookie = new Cookie("JSESSIONID",sessionID);
        cookie.setMaxAge(7*24*3600);//1周的超时时间
        cookie.setPath("/");
        response.addCookie(cookie);
        //手动设置这一个session的超时时间
        //不会影响其他session,单位是 秒

//        session.setMaxInactiveInterval(30);
        //立即销毁session
        //注销功能
        session.invalidate();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request,response);

    }
}
